package com.linln.config.listener;

import cn.hutool.core.util.StrUtil;
import com.linln.common.constant.ParamConst;
import com.linln.common.enums.StatusEnum;
import com.linln.modules.system.domain.Menu;
import com.linln.modules.system.domain.Param;
import com.linln.modules.system.domain.Role;
import com.linln.modules.system.domain.permission.NBSysResource;
import com.linln.modules.system.repository.MenuRepository;
import com.linln.modules.system.repository.ParamRepository;
import com.linln.modules.system.repository.RoleRepository;
import com.linln.modules.system.repository.permission.ResourceRepository;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Arrays;


import static com.linln.common.constant.ParamConst.INIT_NOT;
import static com.linln.common.constant.ParamConst.INIT_STATUS;


/**
 * created by Wuwenbin on 2018/8/1 at 20:25
 *
 * @author wuwenbin
 */
@Component
@Order(2)
@Slf4j
public class MenuListener implements ApplicationListener<ApplicationReadyEvent> {

    private final MenuRepository menuRepository;
    private final RoleRepository roleRepository;
    private final ResourceRepository resourceRepository;
    private final ParamRepository paramRepository;
    private final Environment environment;

    @Autowired
    public MenuListener(MenuRepository menuRepository, RoleRepository roleRepository,
                        ParamRepository paramRepository, ResourceRepository resourceRepository,
                        Environment environment) {
        this.menuRepository = menuRepository;
        this.roleRepository = roleRepository;
        this.paramRepository = paramRepository;
        this.resourceRepository = resourceRepository;
        this.environment = environment;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        Param nbParam = paramRepository.findFirstByName(INIT_STATUS);
   //     long cnt = menuRepository.count();
     //   long rootCnt = menuRepository.countByType(NBSysMenu.MenuType.ROOT.name());
        if (nbParam == null || StringUtils.isEmpty(nbParam.getValue())) {
            throw new RuntimeException("初始化参数有误，未找到 init_status 参数！");
        } else if (nbParam.getValue().equals(INIT_NOT)) {
            log.info("「小懒虫」App 正在初始化菜单，请稍后...");
//            Object[][] folderMenus = new Object[][]{
//                    {"系统管理", "layui-icon layui-icon-auz", new String[][]{
//                            {"/system/menu/index", "菜单管理", "fa fa-list-ul"}
//                            , {"/system/role/index", "角色管理", "fa fa-user-o"}
//                            , {"/system/user/index", "用户管理", "fa fa-users"}
//                    }}
//            };
            String[][] folderMenus = new String[][]{
                    {"主页", "0", "[0]", "/index","layui-icon layui-icon-home","1","1"},
                    {"系统管理", "0", "[0]", "#","fa fa-cog","1","2"},
                    {"菜单管理", "2", "[0][2]", "/system/menu/index","","2","3"},
                    {"角色管理", "2", "[0][2]", "/system/role/index","","2","2"},
                    {"用户管理", "2", "[0][2]", "/system/user/index","","2","1"},
            };
         //   setUpMenuSystem(folderMenus);

        }
     //   hideAuthMenu();
        log.info("「小懒虫」App 初始化菜单完毕");
    }

//    /**
//     * 查找root 菜单的 id
//     *
//     * @return
//     */
//    private long findRootId() {
//        return menuRepository.findByType(NBSysMenu.MenuType.ROOT).getId();
//    }
//
//    /**
//     * 拼接菜单
//     *
//     * @param icon
//     * @param name
//     * @param orderIndex
//     * @param parentId
//     * @param roleId
//     * @param type
//     * @return
//     */
//    private NBSysMenu fixMenu(String icon, String name, int orderIndex,
//                              long parentId, long roleId, NBSysMenu.MenuType type) {
//        return NBSysMenu.builder()
//                .icon(icon)
//                .name(name)
//                .parentId(parentId)
//                .type(type)
//                .enable(true)
//                .orderIndex(orderIndex)
//                .roleId(roleId)
//                .build();
//
//    }

    /**
     * 初始化菜单权限
     */
    private void setUpMenuSystem(String[][] folderMenus) {
        Arrays.stream(folderMenus).forEach(
                hpw -> {
                    int i =0;
                    Menu item = Menu.builder()
                            .title(hpw[i++])
                            .pid(Long.parseLong(hpw[i++]))
                            .pids(hpw[i++])
                            .url(hpw[i++])
                            .icon(hpw[i++])
                            .type(Byte.parseByte(hpw[i++]))
                            .sort(Integer.parseInt(hpw[i++]))
                            .status(StatusEnum.OK.getCode())
                            .build();
                    //保存每个设置的初始值
                    menuRepository.saveAndFlush(item);
                }
        );
    }

//    /**
//     * 更新权限菜单状态
//     */
//    private void hideAuthMenu() {
//        String[] menus = new String[]{
//                "/management/menu",
//                "/management/role",
//                "/management/users"
//        };
//        boolean enable = environment.getProperty("noteblog.menu.auth", Boolean.class, false);
//        for (String menu : menus) {
//            NBSysResource r = resourceRepository.findByUrl(menu);
//            NBSysMenu m = menuRepository.findByResourceId(r.getId());
//            menuRepository.updateEnableById(enable, m.getId());
//        }
//        menuRepository.updateAuthParentMenu(enable);
//    }
//
//
//    /**
//     * 新增一个顶级菜单
//     *
//     * @param icon
//     * @param name
//     * @param url
//     * @param rootId
//     * @param roleId
//     */
//    private void saveTopMenu(String icon, String name, String url, long rootId, long roleId) {
//        NBSysMenu menu = fixMenu(icon, name, 0, rootId, roleId, PARENT);
//        NBSysMenu genMenu = menuRepository.save(menu);
//        NBSysResource genMenuRes = resourceRepository.findByUrl(url);
//        menuRepository.updateResourceById(genMenu.getId(), genMenuRes.getName(), genMenuRes);
//    }
}
